import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:goumao_app/Controller/gm_cw_type.dart';
import 'package:goumao_app/Customs/gm_app_util.dart';
import 'package:goumao_app/Model/gm_cw_type_model.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart'
    as iOSDatePicker;

import '../Model/gm_my_pets.dart';

class GMCWDananScreen extends StatefulWidget {
  final GMPetList? mData;
  const GMCWDananScreen({super.key, this.mData});

  @override
  // ignore: library_private_types_in_public_api
  _GMCWDananScreenState createState() => _GMCWDananScreenState();
}

class _GMCWDananScreenState extends State<GMCWDananScreen> {
  bool isHaveImage = false;
  late File _image;
  late String sex;
  late String pinzhong;
  late String birthday;
  late String imgUrl;
  final TextEditingController _nameController = TextEditingController();

  @override
  void initState() {
    super.initState();
    sex = '';
    birthday = "";
    pinzhong = "";
    imgUrl = "";

    if (widget.mData != null) {
      _nameController.text = widget.mData!.nickname!;
      sex = widget.mData!.gender! == 1 ? "GG" : "MM";
      birthday = widget.mData!.birthday!;
      pinzhong = widget.mData!.categoryName!;
      imgUrl = widget.mData!.coverUrl!;
    }
    setState(() {});
  }

  void _showGenderSelection(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SafeArea(
            child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            const SizedBox(
              height: 50,
              child: Center(
                child: Text(
                  "请选择宠物性别",
                ),
              ),
            ),
            ListTile(
              title: const Center(
                child: Text('GG'),
              ),
              onTap: () {
                _selectGender('GG', context);
              },
            ),
            ListTile(
              title: const Center(
                child: Text('MM'),
              ),
              onTap: () {
                _selectGender('MM', context);
              },
            ),
          ],
        ));
      },
    );
  }

  // 打开图片浏览器
  Future _getImage() async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.gallery);

    setState(() {
      if (pickedFile != null) {
        _image = File(pickedFile.path);
        isHaveImage = true;
      } else {}
    });
  }

  void _selectGender(String gender, BuildContext context) {
    setState(() {
      sex = gender;
    });
    // 关闭底部弹出框
    Navigator.of(context).pop();
  }

  void _showBirthdayPicker(BuildContext context) {
    iOSDatePicker.DatePicker.showDatePicker(
      context,
      pickerMode: iOSDatePicker.DateTimePickerMode.date,
      minDateTime: DateTime(2000, 1, 1),
      maxDateTime: DateTime(
          DateTime.now().year, DateTime.now().month, DateTime.now().day),
      initialDateTime: DateTime.now(),
      dateFormat: "yyyy年,MM|dd",
      pickerTheme: const iOSDatePicker.DateTimePickerTheme(
        confirm: Text(
          "完成",
          style: TextStyle(
              color: Color(0xff73ed94),
              fontSize: 15,
              fontWeight: FontWeight.w400),
        ),
      ),
      onChange: (datetime, selectedIndex) {
        setState(() {
          birthday = DateFormat('yyyy-MM-dd').format(datetime);
        });
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    double avatarViewWH = 80;
    return Scaffold(
      backgroundColor: const Color(0xffF8F8F8),
      appBar: AppBar(
        elevation: 0,
        title: const Text(
          '宠物档案',
          style: TextStyle(
              color: Color(0xff333333),
              fontSize: 16,
              fontWeight: FontWeight.w800),
        ),
      ),
      body: SafeArea(
        child: Column(
          children: [
            // 可滑动的页面
            Expanded(
              child: SingleChildScrollView(
                  child: Container(
                padding: const EdgeInsets.fromLTRB(16, 0, 16, 0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(
                      height: 182,
                      child: Stack(
                        children: [
                          Positioned(
                              left: ((GMAppUtil.kScreenWidth - 24) -
                                      avatarViewWH) *
                                  0.5,
                              top: 60,
                              child: InkWell(
                                onTap: () => {_getImage()},
                                child: ClipRRect(
                                    borderRadius: const BorderRadius.only(
                                      bottomRight: Radius.circular(8),
                                      bottomLeft: Radius.circular(20),
                                      topLeft:
                                          Radius.circular(20.0), // 仅顶部左角为圆角
                                      topRight:
                                          Radius.circular(20.0), // 仅顶部右角为圆角
                                    ), // 设置圆角的大小
                                    child: isHaveImage
                                        ? Image.file(
                                            _image,
                                            width: avatarViewWH,
                                            height: avatarViewWH,
                                            fit: BoxFit.cover,
                                          )
                                        : imgUrl.isNotEmpty
                                            ? Image.network(
                                                imgUrl,
                                                width: avatarViewWH,
                                                height: avatarViewWH,
                                                fit: BoxFit.cover,
                                              )
                                            : Image.asset(
                                                "assets/images/gm_mr_tx_icon.png",
                                                width: avatarViewWH,
                                                height: avatarViewWH,
                                                fit: BoxFit.cover,
                                              )),
                              )),
                          Positioned(
                              left: ((GMAppUtil.kScreenWidth - 24) -
                                          avatarViewWH) *
                                      0.5 +
                                  avatarViewWH -
                                  20,
                              top: 60 + avatarViewWH - 20,
                              child: Image.asset(
                                "assets/images/gm_xj_icon.png",
                                width: 20,
                                height: 20,
                              )),
                        ],
                      ),
                    ),
                    const SizedBox(
                      height: 50,
                    ),
                    Container(
                      padding: const EdgeInsets.fromLTRB(12, 0, 10, 0),
                      height: 50,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4),
                          color: const Color(0xffffffff)),
                      child: Row(
                        children: [
                          const Text(
                            "宠物昵称",
                            style: TextStyle(
                                color: Color(0xff666666),
                                fontSize: 15,
                                fontWeight: FontWeight.w800),
                          ),
                          const Spacer(),
                          Expanded(
                            child: CupertinoTextField(
                              maxLength: 11,
                              // onChanged: _phoneTextChanged,
                              controller: _nameController,
                              placeholder: "输入宠物昵称",
                              textAlign: TextAlign.right,
                              style: const TextStyle(
                                  color: Color(0xff333333),
                                  fontSize: 16,
                                  fontWeight: FontWeight.w500),
                              placeholderStyle: const TextStyle(
                                  color: Color(0xFF999999), fontSize: 14),
                              keyboardType: TextInputType.phone,
                              decoration: const BoxDecoration(
                                color: Color(0xffffffff), // 设置背景颜色
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(
                      height: 16,
                    ),
                    GMDananItem(
                      title: "宠物性别",
                      placeTitle: "点击选择性别",
                      value: sex,
                      onTap: () => {_showGenderSelection(context)},
                    ),
                    GMDananItem(
                      title: "宠物品种",
                      placeTitle: "点击选择品种",
                      value: pinzhong,
                      onTap: () async {
                        // 跳转到B页面，并等待返回结果
                        final result = await Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => const GMCWTypeScreen()));

                        // 处理从B页面返回的结果
                        if (result != null && result is GMCWTypeData) {
                          setState(() {
                            pinzhong = result.name!;
                          });
                        }
                      },
                    ),
                    GMDananItem(
                      title: "出生日期",
                      placeTitle: "点击选择生日",
                      value: birthday,
                      onTap: () => {_showBirthdayPicker(context)},
                    ),
                    const SizedBox(
                      height: 8,
                    ),
                    const Text(
                      "Tip；如果生日不记得了，可以填写到家日期",
                      style: TextStyle(
                          color: Color(0xff999999),
                          fontSize: 11,
                          fontWeight: FontWeight.w300),
                    )
                  ],
                ),
              )),
            ),
            // 底部固定高度的 Container
            Container(
              height: 74.0,
              padding: const EdgeInsets.fromLTRB(33, 0, 33, 20),
              child: InkWell(
                child: Container(
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(25),
                      color: const Color(0xffFF6A6E)),
                  child: const Center(
                    child: Text(
                      "保存",
                      style: TextStyle(
                          color: Color(0xffffffff),
                          fontSize: 15,
                          fontWeight: FontWeight.w400),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class GMDananItem extends StatelessWidget {
  final String title;
  final String placeTitle;
  final String value;
  final GestureTapCallback? onTap;
  final EdgeInsetsGeometry? padding;

  const GMDananItem(
      {super.key,
      required this.title,
      required this.placeTitle,
      this.onTap,
      required this.value,
      this.padding});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: padding ?? const EdgeInsets.fromLTRB(12, 0, 10, 0),
      height: 50,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4),
          color: const Color(0xffffffff)),
      child: Row(
        children: [
          Text(
            title,
            style: const TextStyle(
                color: Color(0xff666666),
                fontSize: 15,
                fontWeight: FontWeight.w800),
          ),
          const Spacer(),
          InkWell(
            onTap: onTap,
            child: Text(
              value.isNotEmpty ? value : placeTitle,
              style: TextStyle(
                  color: value.isNotEmpty
                      ? const Color(0xff333333)
                      : const Color(0xff999999),
                  fontSize: 14),
            ),
          ),
          const SizedBox(
            width: 4,
          ),
          const Icon(
            Icons.chevron_right,
            color: Colors.grey,
          ),
        ],
      ),
    );
  }
}
